package com.gdty.sqlite.utils;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.gdty.sqlite.vo.SQLVo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DbManger {

    private static final String TAG = "DbManger";
    private DBHelper helper; //建立一个数据库对象

    public DbManger(Context ctx, String dbPath, int version, SQLVo vo){
        Log.e(TAG,"管理器初始化！");
        helper= new DBHelper(ctx,dbPath,version,vo);
    }

    public SQLiteDatabase getWritableDatabase(){
        Log.e(TAG, "获取写");
        return helper.getWritableDatabase();
    }

    public SQLiteDatabase getReadableDatabase(){
        Log.e(TAG, "获取读");
        return helper.getReadableDatabase();
    }

    /**
     * 查询
     */
    public List<Map<String,Object>> query(String table, String selection, String[] selectionArgs, String orderBy){
        Log.e(TAG, "[query]查询");
        SQLiteDatabase db = getReadableDatabase();
        List<Map<String,Object>> result = new ArrayList<>();
        try {
            // 执行记录查询动作，该语句返回结果集的游标
            Cursor cursor = db.query(table, null, selection, selectionArgs, null, null, orderBy);
            Log.e(TAG, "[query]查询-返回结果");
            // 循环取出游标指向的每条记录
            while (cursor.moveToNext()) {
                String[] columnNames = cursor.getColumnNames();

                Map<String,Object> entry = new HashMap<>();
                for(String str:columnNames){
                    int index = cursor.getColumnIndex(str);
                    int type = cursor.getType(index);
                    if(Cursor.FIELD_TYPE_STRING==type){
                        String val = cursor.getString(cursor.getColumnIndex(str));
                        entry.put(str,val);
                    }else if(Cursor.FIELD_TYPE_INTEGER==type){
                        Integer val = cursor.getInt(cursor.getColumnIndex(str));
                        entry.put(str,val);
                    }else if(Cursor.FIELD_TYPE_FLOAT==type){
                        Float val = cursor.getFloat(cursor.getColumnIndex(str));
                        entry.put(str,val);
                    }else if(Cursor.FIELD_TYPE_BLOB==type){
                        byte[] val = cursor.getBlob(cursor.getColumnIndex(str));
                        entry.put(str,val);
                    }else{
                        entry.put(str,null);
                    }
                }

                result.add(entry);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (db != null) {
                db.close();
            }
        }
        Log.e(TAG, "[query]查询-返回结果："+JsonUtils.serialize(result));
        return result;
    }

    /**
     * 查询
     */
    public String queryStr(String table, String selection, String[] selectionArgs, String orderBy){
        Log.e(TAG, "[queryStr]查询");
        List<Map<String,Object>> result = query(table, selection, selectionArgs, orderBy);
        String res = JsonUtils.serialize(result);
        Log.e(TAG, "[query]查询-返回结果："+res);
        return res;
    }

    /**
     * 执行sql
     * @param sql
     */
    public void execSQL(String sql){
        Log.e(TAG, "[execSQL]执行sql："+sql);
        SQLiteDatabase db = getWritableDatabase();
        db.beginTransaction();
        try {
            db.execSQL(sql);
            db.setTransactionSuccessful();
            db.endTransaction();
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG,e.getMessage());
        } finally {
            db.close();
        }
        Log.e(TAG, "[execSQL]执行sql[完成]："+sql);
    }

    /**
     * 执行sql
     * @param sqls
     */
    public void execMoreSQL(String[] sqls){
        Log.e(TAG, "[execMoreSQL]执行多条sql："+sqls.toString());
        SQLiteDatabase db = getWritableDatabase();
        db.beginTransaction();
        try {
            for(String sql:sqls){
                db.execSQL(sql);
            }
            db.setTransactionSuccessful();
            db.endTransaction();
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG,e.getMessage());
        } finally {
            db.close();
        }
        Log.e(TAG, "[execMoreSQL]执行多条sql[完成]："+sqls.toString());
    }
}
